package com.example.extra.filter;

import com.example.extra.common.Constants;
import com.example.extra.enums.ErrorEnum;
import com.example.extra.exception.BizException;
import com.example.extra.service.lmpl.UserDetailsServiceImpl;
import com.example.extra.utils.IPUtils;
import com.example.extra.utils.JwtUtils;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

@Slf4j
@Component
public class AuthTokenFilter extends OncePerRequestFilter {


    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private UserDetailsServiceImpl userDetailsService;

    private static final AntPathMatcher antPathMatcher = new AntPathMatcher();


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        try {
            setRequest(request, response);

            String requestURI = request.getRequestURI();

            // 检查请求URI是否匹配跳过列表中的模式
            boolean shouldSkip = Constants.skipList.stream()
                    .anyMatch(pattern -> antPathMatcher.match(pattern, requestURI));

            if(!shouldSkip){
                String jwt = jwtUtils.parseToken(request);

                if (jwt != null && jwtUtils.validateToken(jwt) && !jwtUtils.isTokenBlacklisted(jwt)) {
                    String username = jwtUtils.getUsernameFromToken(jwt);

                    UserDetails userDetails = userDetailsService.loadUserByUsername(username);

                    UsernamePasswordAuthenticationToken authentication =
                            new UsernamePasswordAuthenticationToken(
                                    userDetails,
                                    null,
                                    userDetails.getAuthorities());

                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));

                    SecurityContextHolder.getContext().setAuthentication(authentication);
                }
            }

        } catch (Exception e) {
            throw new BizException(ErrorEnum.UNAUTHORIZED.getCode(), e.getMessage());
        }

        filterChain.doFilter(request, response);
    }


    protected void setRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        // 获取客户端真实IP
        String clientIp = IPUtils.getClientRealIp(request);

        // 获取其他感兴趣的请求信息
        String requestMethod = request.getMethod();
        String requestUri = request.getRequestURI();
        String queryString = request.getQueryString();
        String userAgent = request.getHeader("User-Agent");
        String sessionId = request.getSession().getId();

        // 构建日志消息
        String logMessage = String.format(
                "Client IP: %s | Method: %s | URI: %s | Query: %s | Session: %s | Agent: %s",
                clientIp, requestMethod, requestUri,
                (queryString != null) ? queryString : "None",
                sessionId, userAgent
        );

        // 记录日志（可根据需要调整级别）
        logger.info(logMessage);

        // 可选：将IP等信息设置为请求属性，供控制器或后续流程使用
        request.setAttribute("clientRealIp", clientIp);

    }
}
